/**
 * 表单验证及提交过滤工具
 */
define('form', ['layui', 'message', 'files'], function (undefined, msg) {
    var form = layui.form
        , laydate = layui.laydate
        , $body = $('body')
        , FormController = new function () {
        var that = this;
        // 内容区选择器
        this.targetClass = '.layui-layout-admin>.layui-body';
        // 刷新当前页面
        this.reload = function () {
            // window.onhashchange.call(this);
            window.location.reload();
        };
        // 内容区域动态加载后初始化
        this.reInit = function (container) {
            var container = container ? container: $body
                ,$form = container.find('.layui-form');
            if (!$form.size()) return;
            //-- form--start--//
            $form.find('[type=submit]').attr('lay-submit', true).parents('.layui-form-item').addClass('layui-layer-btn')
            $form.find('[required][name]:visible').attr('lay-verify', 'required').parent().prevAll('label').addClass('label-required');
            $form.find('[data-date-range]').map(function () {
                laydate.render({range: true, elem: this});
                this.setAttribute('autocomplete', 'off');
            });
            $form.find('input[data-date]').map(function () {
                var $this = $(this);
                laydate.render({
                    elem: this,
                    type: $(this).data('type') || 'datetime',
                    done: function(value, date, endDate){
                        $this.val(value).trigger('change');
                    }
                });
                this.setAttribute('autocomplete', 'off');
            });
            if ($form.find('input.tableSelect').size() > 0) {
                require(['table-select'],function (call) {
                    //$form 即.layui-form; tableSelect内置了表单，为了避免表单嵌套故使用 $form.parent()
                    call($form.find('input.tableSelect'),$form.parent());
                });
            }
            $form.find('[data-form-loaded]').map(function () {
                $(this).html(this.getAttribute('data-form-loaded') || this.innerHTML);
                $(this).removeAttr('data-form-loaded').removeClass('layui-disabled');
            });
            $form.find('[data-upload-image]').map(function () {
                var mode = $(this).data('upload-image') || 'one';
                if (mode === 'one') {
                    $(this).uploadOneImage();
                } else {
                    $(this).uploadMultipleImage();
                }
            });
            $form.find('[data-upload-video]').map(function () {
                var mode = $(this).data('upload-video') || 'one';
                if (mode === 'one') {
                    $(this).uploadOneVideo();
                } else {
                    $(this).uploadMultipleVideo();
                }
            });
            $form.find('[data-file]:not([data-inited])').map(function (index, elem, $this, field) {
                $this = $(elem), field = $this.attr('data-field') || 'file';
                if (!$this.data('input')) $this.data('input', $('[name="' + field + '"]').get(0));
                $this.uploadFile(function (url) {
                    $($this.data('input')).val(url).trigger('change');
                });
            });
            /*selectN 无限*/
            $form.find('.selectN').map(function () {
                var that = $(this)
                    , id = 'selectN-' + new Date().getTime()
                    , name = that.data('input-name')
                    , url = that.data('source')
                    , title_name = that.data('field') || 'name'
                    , child_name = that.data('child') || 'children'
                    , id_name = that.data('pk') || 'id'
                    , selected = that.data('selected') || ''
                    , extend = that.data('extend')
                    , defaults = selected.toString().indexOf(',') > 0 ? selected.split(',') : [];
                that.attr('id', id);
                 layui.config({
                     base: '/static/admin/js/utils/'
                });
                layui.use(['selectN'], function () {
                    $.post(url, extend, function (response) {
                        if (response.code === 0) return;
                        var selectN = layui.selectN;
                        //无限级分类-所有配置
                        var catIns = selectN({
                            //元素容器【必填】
                            elem: "#" + id
                            //候选数据【必填】
                            , data: response.data
                            //设置了长度
                            , width: null
                            //默认值
                            , selected: defaults
                            //为真只取最后一个值
                            , last: false
                            //空值项提示，可设置为数组['请选择省','请选择市','请选择县']
                            , tips: '请选择'
                            //事件过滤器，lay-filter名 不设置与选择器相同(去#.)
                            , filter: ''
                            //input的name 不设置与选择器相同(去#.)
                            , name: name
                            //数据分隔符
                            , delimiter: ','
                            //数据的键名
                            , field: {idName: id_name, titleName: title_name, childName: child_name}
                            //表单区分 form.render(type, filter); 为class="layui-form" 所在元素的 lay-filter="" 的值
                            , formFilter: null
                        });

                    })
                })
            });
            //-- form --end--//
            /*编辑器*/
            if ($body.find('textarea.editor').size() > 0) {
                require(['ckeditor'], function () {
                    $body.find('textarea.editor').map(function () {
                        var height = $(this).data('height') || 500,
                            option = {height: height};
                        $(this).attr('id', $(this).attr('id') || (Math.random() + '').replace('.', '_'));
                        window.CKEDITOR.replace($(this).attr('id'), option || {});
                    });
                })
            }
            /*! 后台加密登录处理 */
            if (typeof $form.attr('data-login-form') !== 'undefined') {
                require(['md5'], function (md5) {
                    $form.dataCallback = function (data) {
                        data['password'] = md5.hash(md5.hash(data['password']) + data['skey']);
                        if (data['skey']) delete data['skey'];
                        return data;
                    }
                })
            }
            if ($form.find('input.selectpage').size() > 0) {
                require(['selectpage-build'],function (call) {
                    call($form.find('input.selectpage'));
                });
            }
            if(!$form.hasClass('form-search')){
                form.render();
                this.submit($form);
            }
        };
        // 在内容区显示视图
        this.show = function (html) {
            $(this.targetClass).html(html);
            this.reInit(this.targetClass);
        };
        // 异步加载的数据

        this.load = function (url, data, method, callback, loading, tips, time, headers) {
            var index = loading !== false ? $.msg.loading(tips) : 0;
            if (typeof data === 'object' && typeof data['_csrf_'] === 'string') {
                headers = headers || {};
                headers['User-Token-Csrf'] = data['_csrf_'];
                delete data['_csrf_'];
            }
            $.ajax({
                data: data || {}, type: method || 'GET', url: url, beforeSend: function (xhr) {
                    if (typeof Pace === 'object') Pace.restart();
                    if (typeof headers === 'object') for (var i in headers) xhr.setRequestHeader(i, headers[i]);
                }, error: function (XMLHttpRequest) {
                    if (parseInt(XMLHttpRequest.status) === 200) this.success(XMLHttpRequest.responseText);
                    else $.msg.tips('E' + XMLHttpRequest.status + ' - 服务器繁忙，请稍候再试！');
                }, success: function (ret) {
                    if (typeof callback === 'function' && callback.call(that, ret) === false) return false;
                    return typeof ret === 'object' ? $.msg.auto(ret, time || ret.wait || undefined) : that.show(ret);
                }, complete: function () {
                    $.msg.close(index);
                }
            });
        };
        // 加载HTML到目标位置
        this.open = function (url, data, callback, loading, tips) {
            this.load(url, data, 'get', function (ret) {
                return typeof ret === 'object' ? $.msg.auto(ret) : that.show(ret);
            }, loading, tips);
        };
        // 打开一个iframe窗口
        this.iframe = function (url, title, area) {
            return layer.open({
                offset: '20%',
                title: title || '窗口',
                type: 2,
                area: area || ['800px', '550px'],
                fix: true,
                maxmin: false,
                content: url
            });
        };
        // 加载HTML到弹出层
        this.modal = function (url, data, title, callback, loading, tips) {
            this.load(url, data, 'GET', function (res) {
                if (typeof (res) === 'object') return $.msg.auto(res);
                var area = [$(window).width() > 800 ? '800px' : 'auto', $(window).height() > 600 ? '600px' : 'auto'];
                var index = layer.open({
                    type: 1,
                    btn: false,
                    maxmin: true,
                    area: area,
                    shade: 0,
                    offset: '100px',
                    content: res,
                    title: title || '',
                    success: function (dom, index) {
                        $(dom).find('[data-close]').off('click').on('click', function () {
                            if ($(this).attr('data-confirm')) return $.msg.confirm($(this).attr('data-confirm'), function (_index) {
                                layer.close(_index), layer.close(index);
                            }), false;
                            layer.close(index);
                        });
                        $.form.reInit($(dom));
                    }
                });
                $.msg.indexs.push(index);
                return (typeof callback === 'function') && callback.call(this);
            }, loading, tips);
        };

        // form.on = function (e, i) {
        //     return layui.onevent.call(this, 'form', e, i)
        // }
        this.submit = function ($forms) {
            $forms.map(function(key, form) {
                var loadings = [];
                var $form = $(form);
                $form.on('submit', function (result) {
                    if (typeof CKEDITOR === 'object' && typeof CKEDITOR.instances === 'object') {
                        for (var i in CKEDITOR.instances) CKEDITOR.instances[i].updateElement();
                    }
                    var data = $form.serializeObject();
                    //可以在$('.layui-form') 上添加 dataFilter 属性作为过滤函数名
                    var filter = $form.attr('data-callback') || $form.dataCallback || $forms.dataCallback
                        , headers = {}
                        , method = $form.attr('method') || 'POST'
                        , url = $form.attr('action') || '';
                    if (typeof filter === 'function') {
                        // 如果数据过滤失败
                        if ((data = filter(data)) === false) {
                            return false;
                        }
                    }
                    var index = msg.loading();
                    if (typeof data === 'object' && typeof data['_csrf_'] === 'string') {
                        headers['User-Token-Csrf'] = data['_csrf_'];
                        delete data['_csrf_'];
                    }
                    // if(loadings[url] === true) return;
                    // loadings[url] = true;
                    $.ajax({
                        data: data || {}, type: method || 'GET', url: url, beforeSend: function (xhr) {
                            if (typeof Pace === 'object') Pace.restart();
                            if (typeof headers === 'object') for (var i in headers) xhr.setRequestHeader(i, headers[i]);
                        }, error: function (XMLHttpRequest) {
                            if (parseInt(XMLHttpRequest.status) === 200) this.success(XMLHttpRequest.responseText);
                            else msg.tips('E' + XMLHttpRequest.status + ' - 服务器繁忙，请稍候再试！');
                        }, success: function (ret) {
                            if (typeof dataResult === 'function') {
                                if (dataResult(ret) === false) return false;
                            }
                            var url = ret.url || (typeof ret.data === 'string' ? ret.data : '');
                            var mg = ret.msg || (typeof ret.info === 'string' ? ret.info : '');
                            if (ret.code === 1) {
                                msg.success(mg, 1.5, function () {
                                    return url ? (window.location.href = url) : window.location.reload()
                                });
                            } else {
                                msg.error(mg, 1.5);
                            }
                        }, complete: function () {
                            // setTimeout(function(){
                            //     loadings[url] = false;
                            // }, time || 1500);
                            msg.close(index);
                        }
                    });
                    return event.preventDefault(), false;
                });
            });
        };
        /*! 表单转JSON */
        $.fn.serializeObject = function () {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
        !function (_this) {
            _this.reInit();
        }(this)
    };
    $.form = FormController;
    return FormController
});